<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row>
        <el-col :span="20">
          <span>选择商品分类：</span>
          <el-cascader
            expand-trigger="hover"
            v-model="selected"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"
            clearable
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="sel" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisable"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="tagClose(i,scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="editDialog(scope.row.attr_id)"
                  icon="el-icon-edit"
                  circle
                ></el-button>
                <el-button
                  type="danger"
                  @click="remove(scope.row.attr_id)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisable"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyData" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                   @close="tagClose(i,scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="editDialog(scope.row.attr_id)"
                  icon="el-icon-edit"
                  circle
                ></el-button>
                <el-button
                  type="danger"
                  @click="remove(scope.row.attr_id)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titlePacks"
      :visible.sync="addDialogVisible"
      @closed="editDialogVisibleClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titlePacks" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titlePacks"
      :visible.sync="editDialogVisible"
      @closed="editDialogVisibleClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titlePacks" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      parentCateList: [],
      selected: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      sel: "many",
      manyData: [],
      onlyData: [],
      editDialogVisible: false,
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      editForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入属性名称",
          },
        ],
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入属性名称",
          },
        ],
      },
    }
  },
  created() {
    this.getParams()
  },
  computed: {
    isBtnDisable() {
      if (this.selected.length !== 3) {
        return true
      } else {
        return false
      }
    },
    titlePacks() {
      if (this.sel === "many") {
        return "动态参数"
      } else {
        return "静态属性"
      }
    },
  },
  methods: {
    async getParams() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 },
      })
      if (res.meta.status !== 200) return this.$message.error("获取列表失败")
      this.parentCateList = res.data
    },
    parentCateChange() {
      this.getData()
    },
    handleClick() {
      this.getData()
    },
    async getData() {
      if (this.selected.length !== 3) {
        this.selected = []
        this.manyData=[]
        this.onlyData=[]
        return false
      }
      const { data: res } = await this.$http.get(
        `categories/${this.selected[this.selected.length - 1]}/attributes`,
        { params: { sel: this.sel } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败")
      }

      for (var i = 0; i < res.data.length; i++) {
        if (res.data[i].attr_vals !== "") {
          res.data[i].attr_vals = res.data[i].attr_vals.split(" ")
        } else {
          res.data[i].attr_vals = []
        }
        res.data[i].inputVisible = false
        res.data[i].inputValue = ""
      }
      if (this.sel === "many") {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    editDialogVisibleClose() {
      if (this.editDialogVisible === true) {
        this.editDialogVisible = false
        this.$refs.editFormRef.resetFields()
      }
      if (this.addDialogVisible === true) {
        this.addDialogVisible = false
        this.$refs.addFormRef.resetFields()
      }
    },
    add() {
      this.$refs.addFormRef.validate(async (resa) => {
        if (!resa) {
          return
        }
        const { data: res } = await this.$http.post(
          `categories/${this.selected[this.selected.length - 1]}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.sel }
        )
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败")
        }
        this.$message.success("添加成功")
        this.addDialogVisible = false
        this.getData()
      })
    },
    async editDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${
          this.selected[this.selected.length - 1]
        }/attributes/${attr_id}`,
        { attr_name: this.addForm.attr_name, attr_sel: this.sel }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败")
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    async remove(attr_id) {
      const result = await this.$confirm(
        "此操作将删除该参数，是否取消",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err)
      if (result !== "confirm") return this.$message.info("已取消删除！")
      const { data: res } = await this.$http.delete(
        `categories/${
          this.selected[this.selected.length - 1]
        }/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败")
      }
      this.$message.success("删除成功")
      this.getData()
    },
    edit() {
      this.$refs.editFormRef.validate(async (resa) => {
        if (!resa) {
          return
        }
        const { data: res } = await this.$http.put(
          `categories/${this.selected[this.selected.length - 1]}/attributes/${
            this.editForm.attr_id
          }`,
          { attr_name: this.editForm.attr_name, attr_sel: this.sel }
        )
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败")
        }
        this.$message.success("修改成功")
        this.editDialogVisible = false
        this.getData()
      })
    },
    async saveTag(row) {
      const { data: res } = await this.$http.put(
        `categories/${
          this.selected[this.selected.length - 1]
        }/attributes/${row.attr_id}`,{
          attr_vals:row.attr_vals.join(' '),
          attr_sel:row.attr_sel,
          attr_name:row.attr_name
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("操作失败")
      }
      this.$message.success("操作成功")
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ""
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      this.saveTag(row)
      row.inputValue = ""
      row.inputVisible = false
    },
    tagClose(data,row){
      row.attr_vals.splice(data,1)
      this.saveTag(row)
    }

  },
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-link--inner {
  line-height: 60px;
  text-align: center;
}
.el-tag--light {
  margin: 0 5px;
}
.input-new-tag {
  width: 80px;
}
</style>